<?php


namespace app\api\controller;

use app\api\model\Account as AccountModel;

class Account
{

    //增
    public function add()
    {
        $no = input('get.no');
        $name = input('get.name');
        $gender = input('get.gender');
        $accountModel = new AccountModel();
        if ($accountModel->where('account_no', '=', $no)->find()) {
            return '学号已存在，请更换。';
        }
        $data = array();
        $data['account_no'] = $no;
        $data['account_name'] = $name;
        $data['account_gender'] = $gender;
        $data['add_time'] = time();
        return $accountModel->insert($data);
    }

    //删
    public function del()
    {
        $id = input('get.id');
        $accountModel = new AccountModel();
        if (empty($id)) {
            //  <>表示不等于
            return $accountModel->where('account_id', '<>', '0')->delete();
        } else {
            return $accountModel->where('account_id', 'in', $id)->delete();
        }
    }

    //查
    public function sel()
    {
        $keyword = input('get.keyword');
        $condition = array();
        if (!empty($keyword)) {
            $condition[] = ['account_no|account_name', 'like', '%' . $keyword . '%'];
        }
        $data = array();
        $data['code'] = 0;
        $data['msg'] = '';
        $data['count'] = 1000;
        $accountModel = new AccountModel();
        $array = $accountModel->where($condition)->select();
        foreach ($array as $item) {
            #第一次循环 $item =>  {"account_id":1,"account_name":"张三"}
            #第二次循环 $item =>  {"account_id":2,"account_name":"张三"}
            $item['gender_name'] = $item['account_gender'] == 1 ? '男' : '女';
            $item['add_time_name'] = date('Y年m月d日 H:i:s', $item['add_time']);
        }
        $data['data'] = $array;
        header('content-type:application/javascript');
        echo json_encode($data);
        die();
    }

    //改
    public function edit()
    {
        $id = input('get.id');
        $name = input('get.name');
        $gender = input('get.gender');
        if (empty($id)) return '请输入ID';
        if (empty($name)) return '请输入姓名';
        if (empty($gender)) return '请输入性别';
        $accountModel = new AccountModel();
        if (!$accountModel->where('account_id', '=', $id)->find()) {
            return '此用户不存在，无法修改。';
        }
        $update = array();
        $update['account_name'] = $name;
        $update['account_gender'] = $gender;
        return $accountModel->where('account_id', '=', $id)->update($update);
    }

}